/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        //零个节点或者一个结点   无环
        if(head == null || head.next == null){
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(true){
            if(fast == null || fast.next == null){
                //不能调换位置 从左到右会越界
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                break;
            }
        }

        //有环
        fast = head;
        while(fast != null || fast.next != null){
            if(fast == slow){
                return fast;
            }
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}